#include "bt_data.h"
#include "Error.h"

#include <ctype.h>
#include <stdlib.h>

#define U_CHAR unsigned char

/* Create a BTData element */
BTData btdata_create (char *key, FreqField field)
{
	BTData d;

	if ((d = (BTData) malloc (sizeof (struct _bt_data))) == NULL)
		Die ("Failed to allocate bt_data element for %s\n", key);

	d->key = key;
	
	if (field == FSTART) {
		d->freq = 1;
	} else {
		d->freq = -1;
	}

	return d;
}

void btdata_free (BTData elmt)
{
	free (elmt);
}

/* This implementation of a case insensitive string comparison
 * function is more efficient on the codon server despite its
 * readability. */
int btdata_keycmp (char *kstatic, char *kdynamic)
{
	U_CHAR *p, *q;
	U_CHAR c1, c2;
	
	p = (U_CHAR *) kstatic;
	q = (U_CHAR *) kdynamic;

	c1 = (U_CHAR) tolower ((int) *p++);
	c2 = (U_CHAR) tolower ((int) *q++);

	while (c1 == c2) {
		c1 = (U_CHAR) tolower ((int) *p++);
		c2 = (U_CHAR) tolower ((int) *q++);

		if (c1 == '\0')
			return c1 - c2;
	}

	return c1 - c2;
}

/* Increment or decrement the frequency field depending on which
 * file we are reading. */
void btdata_increment (BTData d, FreqField f)
{
	if (f == FSTART)
		d->freq++;
	else
		d->freq--;
}
